package com.qen.common;

import lombok.Data;
import org.beetl.sql.clazz.kit.BeetlSQLException;

import java.lang.reflect.Field;

/**
 * 反射字段缓存
 *
 * @author licz
 * @since 1.0.0
 */
@Data
public class FieldCache {

    public Field field;

    public Class<?> type;

    public boolean isAccessible = false;

    public FieldCache(Field field, Class<?> type) {
        this.field = field;
        this.type = type;
        this.isAccessible = true;
    }

    public Object getFieldValue(Object object) {
        try {
            if (!isAccessible) {
                isAccessible = true;
                field.setAccessible(true);
            }
            return field.get(object);
        } catch (IllegalAccessException e) {
            throw new BeetlSQLException(BeetlSQLException.ERROR, e);
        }
    }

    public void setFieldValue(Object source, Object value) {
        try {
            if (!isAccessible) {
                isAccessible = true;
                field.setAccessible(true);
            }
            field.set(source, value);
        } catch (IllegalAccessException e) {
            throw new BeetlSQLException(BeetlSQLException.ERROR, e);
        }
    }
}
